<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 分配重复整数 -->
    <script>
      var canDistribute = function (nums, quantity) {
        let n = nums.length,
          m = quantity.length
        let map = new Map()
        for (let i = 0; i < n; ++i) map.set(nums[i], (map.get(nums[i]) || 0) + 1)
        let map2 = new Map()
        for (let val of map.entries()) map2.set(val[0], val[1])
        quantity.sort((a, b) => b - a)
        const big = map => {
          for (let i = 0; i < m; ++i) {
            let diff = -Infinity,
              index
            for (let val of map.entries()) {
              let temp = val[1] - quantity[i]
              if (temp == 0) {
                index = val[0]
                map.delete(val[0])
                diff = 0
                break
              }
              if (temp > 0 && temp > diff) {
                ;(index = val[0]), (diff = temp)
              }
            }
            if (diff == -Infinity && index == undefined) return false
            map.set(index, map.get(index) - quantity[i])
          }
          return true
        }
        const small = map => {
          for (let i = 0; i < m; ++i) {
            let diff = Infinity,
              index
            for (let val of map.entries()) {
              let temp = val[1] - quantity[i]
              if (temp == 0) {
                index = val[0]
                map.delete(val[0])
                diff = 0
                break
              }
              if (temp > 0 && temp < diff) {
                ;(index = val[0]), (diff = temp)
              }
            }
            if (diff == Infinity && index == undefined) return false
            map.set(index, map.get(index) - quantity[i])
          }
          return true
        }
        return big(map) || small(map2)
      }
      console.log(canDistribute([1, 2, 3, 4], [2]))
    </script>
  </body>
</html>
